/*
 * Copyright 2011-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.mgmt.system.auth.model;

import java.util.List;

import org.springframework.security.core.userdetails.UserDetails;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;

import me.ijleex.mgmt.system.role.entity.Role;

/**
 * 保存在 Jwt 中的用户
 *
 * @author liym
 * @since 2019-12-21 16:30 新建
 */
@SuppressWarnings("serial")
public final class JwtUser implements UserDetails {

    /**
     * JWT的唯一身份标识，主要用来作为一次性Token，从而回避重放攻击。
     *
     * @since 2020-02-02 14:37
     */
    @JsonProperty("jti")
    private Long tokenId;

    /**
     * JWT签发者（签名是由谁生成）
     */
    @JsonProperty("iss")
    private Long userId;
    /**
     * 主题（username）
     */
    @JsonProperty("sub")
    private String username;

    private String password;

    private List<Role> roles;

    /**
     * 用户是否可用
     */
    private boolean enabled;

    private JwtUser() {}

    public JwtUser(String username, boolean enabled) {
        this.username = username;
        this.enabled = enabled;
    }

    public JwtUser(Long userId, String username, String password, List<Role> roles) {
        this.userId = userId;
        this.username = username;
        this.password = password;
        this.roles = roles;
        this.enabled = true;
    }

    public Long getTokenId() {
        return this.tokenId;
    }

    public void setTokenId(Long tokenId) {
        this.tokenId = tokenId;
    }

    public Long getUserId() {
        return this.userId;
    }

    private void setUserId(Long userId) {
        this.userId = userId;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    private void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public List<Role> getAuthorities() {
        return this.roles;
    }

    /**
     * 用户账号是否过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return this.enabled;
    }

    /**
     * 用户账号是否被锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return this.enabled;
    }

    /**
     * 用户密码是否过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 用户是否可用
     */
    @Override
    public boolean isEnabled() {
        return this.enabled;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("tokenId", this.tokenId)
                .add("userId", this.userId)
                .add("username", this.username)
                .toString();
    }

}
